package com.stu.controller;

import cn.hutool.core.util.URLUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.stu.service.ExcelService;
import com.stu.service.StudentsService;
import com.stu.tools.ApiData;
import com.stu.tools.MyTools;
import com.stu.tools.easyexcle.read.DemoDataListener;
import com.stu.tools.easyexcle.write.WriteTest;
import com.stu.vo.ExcelData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/file")
public class ExcelController {
    @Autowired
    ExcelService excelService;
    @Autowired
    StudentsService studentsService;
    @Autowired
    WriteTest writeTest;
    MyTools t = new MyTools();

    @ResponseBody
    @RequestMapping(value = "/excelUpload", method = RequestMethod.POST)
    public ApiData excelUpload(@RequestParam("filename") MultipartFile file) {
        // 获取文件全名
        String originalFilename = file.getOriginalFilename();
        //设置文件路径
        String rootPath = t.getPath("upload/");
        //获取当前时间戳
        String time = String.valueOf(System.currentTimeMillis());
        //重命名文件名
        assert originalFilename != null;
        String rename = time + originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
        //拼接新文件路径
        String newFilePath = rootPath + rename;
        //创建file对象
        excelService.test();
        File newFile = new File(newFilePath);
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
            MyTools.delFile(newFilePath);
            return ApiData.getFalse("Excel上传异常！");
        }
        ExcelReader excelReader = null;
        DemoDataListener listener = new DemoDataListener(excelService);
        try {
            long start = System.currentTimeMillis();
            excelReader = EasyExcel.read(newFilePath, ExcelData.class, listener).build();
            ReadSheet readSheet = EasyExcel.readSheet(0).build();
            excelReader.read(readSheet);
            System.out.print("耗时：");
            System.out.println(System.currentTimeMillis() - start);
        } catch (Exception e) {
            if (e instanceof ExcelDataConvertException) {
                ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) e;
                return ApiData.getFalse("第" + (excelDataConvertException.getRowIndex() + 1) + "行，第" + excelDataConvertException.getColumnIndex() + "列 数据不合法，数据为:" + excelDataConvertException.getCellData());
            }
            return ApiData.getFalse(e.getMessage());
        } finally {
            MyTools.delFile(newFilePath);
            if (excelReader != null) {
                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                excelReader.finish();
            }
        }
        return ApiData.getTrue("Excel导入成功");
    }

    @RequestMapping("/excelDownload")
    @ResponseBody
    public ApiData excelDownload(HttpServletResponse response) {
        try {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("学生基本信息", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ExcelData.class).sheet("学生信息").doWrite(studentsService.studentsList());
        } catch (Exception e) {
            return ApiData.getFalse(e.getMessage());
        }
        return ApiData.getTrue("导出成功");
    }

    @RequestMapping("/excelModDownload")
    @ResponseBody
    public ApiData excelModDownload(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + URLUtil.encode("数据导入模板") + ".xlsx");
            // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
            EasyExcel.write(response.getOutputStream(), ExcelData.class).sheet("模板").doWrite(writeTest.data());
        } catch (Exception e) {
            return ApiData.getFalse(e.getMessage());
        }
        return ApiData.getTrue("模板下载成功");
    }
}